package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.HnaPayConstants;
import com.gopay.common.constants.bank.HnaPayOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.hnapay.ebank.query.HnaPayMessageQuery;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.MoneyUtil;
import com.gopay.remote.bank.BankInteractRemoteService;

public class CheckOrderHnaPayImpl implements BankOrderService {
	 private Logger logger = Logger.getLogger("HNAPAY");
	    @Resource(name = "bankClient")
	    private BankInteractRemoteService bankClient;
	    
		@Override
		public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
			 CheckOrderResult checkOrderResult = new CheckOrderResult();
			 checkOrderResult.setSuccess(false);
		        checkOrderResult.setOrderId(bankOrder.getOrderId());
		        HnaPayMessageQuery message = new HnaPayMessageQuery();
		        message.setOrderId(bankOrder.getOrderId());
		        message.setBankOrderId(bankOrder.getOutOrderId());
		        message.setBank(BankConstants.BANK_LOGO_HNAPAY);
		        message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
		        message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
		        message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(),"yyyyMMddHHmmss"));//发往银行交易时间
		        message.setBank(bankOrder.getBankCode());
		        if(BankConstants.BANK_LOGO_CEB.equals(bankOrder.getBankCode())){
					message.setOrgCode("ceb");
				}else if(BankConstants.BANK_LOGO_BOCOM.equals(bankOrder.getBankCode())){
					message.setOrgCode("comm");
				}else if(BankConstants.BANK_LOGO_BOC.equals(bankOrder.getBankCode())){
					message.setOrgCode("boc");
				}else if(BankConstants.BANK_LOGO_PAB.equals(bankOrder.getBankCode())){
					message.setOrgCode("sdb");
				}else if(BankConstants.BANK_LOGO_GDB.equals(bankOrder.getBankCode())){
					message.setOrgCode("gdb");
				}else if(BankConstants.BANK_LOGO_CIB.equals(bankOrder.getBankCode())){
					message.setOrgCode("cib");
				}else if(BankConstants.BANK_LOGO_CITIC.equals(bankOrder.getBankCode())){
					message.setOrgCode("ecitic");
				}else if(BankConstants.BANK_LOGO_ABC.equals(bankOrder.getBankCode())){
					message.setOrgCode("abc");
				}else if(BankConstants.BANK_LOGO_CMB.equals(bankOrder.getBankCode())){
					message.setOrgCode("cmb");
				}else{
					logger.error("HNAPAY Bank Code not matches!");
				}
		        Result result = new Result();
		        try {
		            result = bankClient.query(message);
		
			        if (result == null || !result.isSuccess()) {
			            logger.error("bankClient fail.");

						if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
							BankCountDownLatch.failIncrease(bankOrder.getBankCode());
							checkOrderResult.setCommunicateError(true);
						}
						
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			            checkOrderResult.setErrMsg("系统返回对账结果为空");
			            return checkOrderResult;
			        }
		
			        HnaPayMessageQuery res = (HnaPayMessageQuery) result.getDefaultModel();
			        if (res == null) {
			            // 查询订单为空
			            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062
			                    + " err:bis query is null.");
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			            checkOrderResult.setErrMsg("银行返回对账结果为空");
			        }
		
			        if (!StringUtils.equals(HnaPayConstants.TRADE_RETURN_SUCCESS, res.getResultCode())) {
			            // 查询订单错误
			            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" +  res.getResultCode());
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
			            checkOrderResult.setErrMsg("银行返回订单查询失败");
			            return checkOrderResult;
			        }
		
			        if(res.getStateCode() != null&& HnaPayConstants.TRADE_RETURN_SUCCESS.equals(res.getResultCode())){
			        	
			        	String[] arrayQuery = res.getQueryDetails().split(",");
						
			               res.setOrderId(arrayQuery[0]);
			               res.setOrderAmount(arrayQuery[1]);
			               res.setPayAmount(arrayQuery[2]);
			               res.setAcquiringTime(arrayQuery[3]);
			               res.setCompleteTime(arrayQuery[4]);
			               res.setOrderNo(arrayQuery[5]);
			               res.setStateCode(arrayQuery[6]);
			        // 判断交易订单处理状态
			        if (HnaPayConstants.ORDER_STATE_SUCCESS.equals(res.getStateCode())) {
			            checkOrderResult.setSuccess(true);
			            InAccInfo accInfo = new InAccInfo();
				        accInfo.setOrderId(bankOrder.getOrderId());
				        accInfo.setAmount(new BigDecimal(MoneyUtil.formatAmt(res.getPayAmount())));
				        accInfo.setRetCode("00");
				        accInfo.setCardType(BankCardType.Unknown.toString());
				        checkOrderResult.setAccInfo(accInfo);
			            logger.error("新生B2C订单" + bankOrder.getOrderId() + "的交易" + HnaPayOrderStatus.getName(res.getStateCode())+"返回码：" + res.getStateCode());		            
			        } else if(StringUtils.equals(HnaPayConstants.ORDER_STATE_FAILURE, res.getStateCode())){
			        	 // 银行订单状态为失败
			        	checkOrderResult.setBankFailure(true);
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
			            logger.error("新生B2C订单" + bankOrder.getOrderId() + "的交易" + HnaPayOrderStatus.getName(res.getStateCode())+"返回码：" + res.getStateCode());
			            String errMsg = HnaPayOrderStatus.getName(res.getStateCode());
			            if (errMsg != null) {
			                checkOrderResult.setErrMsg(errMsg);
			            } else {
			                checkOrderResult.setErrMsg("对账成功，银行返回交易失败");
			            }
			        }else if(StringUtils.equals(HnaPayConstants.ORDER_STATE_ACCEPT, res.getStateCode())){
			        	 // 银行查询交易已接受
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
			            logger.error("新生B2C订单" + bankOrder.getOrderId() + "的交易" + HnaPayOrderStatus.getName(res.getStateCode())+"返回码：" + res.getStateCode());
			            String errMsg = HnaPayOrderStatus.getName(res.getStateCode());
			            if (errMsg != null) {
			                checkOrderResult.setErrMsg(errMsg);
			            } else {
			                checkOrderResult.setErrMsg("对账成功，银行返回已接受");
			            }
			        }else if(StringUtils.equals(HnaPayConstants.ORDER_STATE_DEALING, res.getStateCode())){
			        	 // 银行查询交易处理中
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
			            logger.error("新生B2C订单" + bankOrder.getOrderId() + "的交易" + HnaPayOrderStatus.getName(res.getStateCode())+"返回码：" + res.getStateCode());
			            String errMsg = HnaPayOrderStatus.getName(res.getStateCode());
			            if (errMsg != null) {
			                checkOrderResult.setErrMsg(errMsg);
			            } else {
			                checkOrderResult.setErrMsg("对账成功，银行返回交易处理中");
			            }
			        }
			        else {
			            // 银行订单状态未知
			            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
			            logger.error("新生B2C订单" + bankOrder.getOrderId() + "的交易未知，返回码：" + res.getStateCode());
			            checkOrderResult.setErrMsg("对账成功，银行返回交易未知");
		
			          }
			        }// 没有查到订单
					else {
						logger.error(" HNAPAY B2C orderId:" + bankOrder.getOrderId()
								+ ",returnMsg:  not found order");
						checkOrderResult
								.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
						checkOrderResult.setErrMsg("银行返回订单未查到");
					}
				    return checkOrderResult;
		        } catch (Exception e) {
		            logger.error("bankClient fail.", e);
		            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
		            checkOrderResult.setErrMsg("银行对账异常");
		            return checkOrderResult;
		        }
		}

		@Override
		public BankOrder getDbOrder() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public BaseMessage dayend(String bank_bus) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public List<CheckOrderResult> checkDayend(String bank_bus) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public Result getDayendMsg(String string) {
			// TODO Auto-generated method stub
			return null;
		}




		@Override
		public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
			// TODO Auto-generated method stub
			return null;
		}

}
